/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-03-23
*/
package com.rzico.article.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.article.entity.ArticleLaud;
import com.rzico.article.entity.ArticleTag;
import com.rzico.article.entity.Talent;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.article.entity.Article;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.article.mapper.ArticleMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <pre>
 * 文章管理业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class ArticleService extends BaseServiceImpl<Article, String> {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private ArticleTagService articleTagService;
    @Autowired
    private TalentService talentService;
    @Autowired
    private ArticleLaudService articleLaudService;
    @Autowired
    private MemberService memberService;


    @Override
    public BaseMapper<Article, String> getMapper() {
        return articleMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    public Article save(Article article, Long[] tagIds, Member member) {
        Enterprise enterprise = enterpriseService.getCurrent();
        //为有手机验证的用户申请达人
        Talent talent = talentService.findByMember(member.getId());
        long talentKey = -1;
        if (talent != null) {
            talent.setModifyDate(new Date());
            article.setTalentId(talent.getId());
            talentService.updateByPrimaryKey(talent);
        } else {
            talent = new Talent();
            talent.setName(member.getName());
            //talent.setModifyDate(new Date());
            talent.setAvatar(member.getAvatar());
            talent.setCreateDate(new Date());
            talent.setLaud(0);
            talent.setHits(0);
            talent.setFollow(0);
            talent.setLove(0);
            talent.setMemberId(member.getId());
            talentKey = talentService.insertUseGeneratedKeys(talent);
        }

        if (talentKey > 0) {
            article.setTalentId(talentKey);
        }
        article.setEnterpriseId(enterprise.getId());
        article.setCreateDate(new Date());
        if(article.getMediaType() == null) {
            article.setMediaType(0);
        }
        if(article.getLinkType() == null) {
            article.setLinkType(0);
        }
        if (article.getAuthor() == null || "".equals(article.getAuthor())) {
            article.setAuthor(talent.getName());
        }
        article.setAvatar(talent.getAvatar());
        article.setDeleted(false);
        super.insertUseGeneratedKeys(article);


        if (tagIds!=null) {
            for (Long tagId : tagIds) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticles(article.getId());
                articleTag.setTags(tagId);
                articleTagService.insert(articleTag);

            }
        }


        return article;
    }


    @Transactional(rollbackFor = Exception.class)
    public Article update(Article article,Long [] tagIds) {

        super.updateByPrimaryKeySelective(article);

        ArticleTag articleTag = new ArticleTag();
        articleTag.setArticles(article.getId());
        articleTagService.delete(articleTag);

        if (tagIds!=null) {

            for (Long tagId : tagIds) {
                articleTag = new ArticleTag();
                articleTag.setArticles(article.getId());
                articleTag.setTags(tagId);
                articleTagService.insert(articleTag);

            }
        }

        return article;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(Object[] ids) {
        int rw = 0;
        for (Object id:ids) {
            Article article = selectByPrimaryKey(id);
            article.setDeleted(true);
            rw = rw + super.updateByPrimaryKeySelective(article);
        }
        return rw;
    }

    public List<Article> findByIds(List<Long> ids) {
        return articleMapper.findByIds(ids);
    }


    public void laudDispose(Map<String, Object> params,Member member, List<Article> list) {
        //如果是达人详情拼接查出来的文章id
        Map<Long, Article> storeArticleId = new HashMap<>();
        if (params.containsKey("talentId")) {
                list.forEach((a) ->{
                storeArticleId.put(a.getId(),a);
            });
            //根据文章idsMap和会员的个人memberId查是否已经对这篇文章点赞
            Map<String, Object> laudParams = new HashMap<>();
            laudParams.put("articleIds", storeArticleId);
            laudParams.put("memberId", member.getId());
            //mapper修改
            List<ArticleLaud> articleLauds = articleLaudService.selectList(laudParams);
            //把查到的文章与分页出的文章进行hash对比
            articleLauds.forEach((a) -> {
                if (storeArticleId.containsKey(a.getArticleId())){
                    storeArticleId.get(a.getArticleId()).setLaud(true);
                }
            });
        }
    }

    /**
     *
     */
    public Long countLaudOrHitsNum(Long talentId, String type) {
        Map<String, Object> params = new HashMap<>();
        params.put("talentId", talentId);
        params.put("type",type);
        List<Long> num = articleMapper.selectLaudOrHisNumSum(talentId, type);
        long sum = num.stream().mapToLong(a -> {
            if (a !=null && a.longValue() != 0){
                return a;
            }else {
                return 0;
            }

        }).sum();
        return sum;
    }

    @Transactional(rollbackFor = Exception.class)
    public void incHits(Article result) {
        //阅读数+1
        Talent talent = talentService.findById(result.getTalentId());
        if (talent != null) {
            if (talent.getHits() == null) {
                talent.setHits(0);
            }
            talent.setHits(talent.getHits()+1);
            talentService.updateByPrimaryKey(talent);
        }
        if (result.getHits() != null) {
            result.setHits(result.getHits()+1);
        } else if (result.getHits() == null) {
            result.setHits(1L);
        }
        super.updateByPrimaryKey(result);
        Member member = memberService.getCurrent();
        Map<String,Object> params2 = new HashMap<>();
        boolean isAlaud = false;
        if (member != null && member.getId() !=null && member.getId() > 0) {
            params2.put("articleId", result.getId());
            params2.put("memberId", member.getId());
            isAlaud = articleLaudService.getIsAlaud(params2);
        }

        result.setLaud(isAlaud);
    }

    public List<Article> showOtherLaudArticle(Long talentId, Integer articleType, Pageable pageable) {
        Talent byMember = talentService.findById(talentId);
        if (byMember == null) {
            throw new CustomException("不存在此达人");
        }
        Map<String,Object> params = new HashMap<>();
        params.put("memberId", byMember.getMemberId());
        params.put("articleType",articleType);
        //分页查询点赞表文章的id,根据我的memberId
        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<ArticleLaud> articleLauds = articleLaudService.selectList(params);
        PageResult<ArticleLaud> pageResult = new PageResult<ArticleLaud>(articleLauds, startPage.getTotal(), pageable);

        //List<Long> collect = articleLauds.stream().map(a -> a.getArticleId()).collect(Collectors.toList());
        Map<Long, Object> articleIds = articleLauds.stream().collect(Collectors.toMap(ArticleLaud::getArticleId, v -> v));
        params.remove("memberId");
        params.put("articleIds", articleIds);
        List<Article> articles = super.selectList(params);
        return articles;
    }
}
